"""
冲突行为检测引擎
实现打架、推搡等冲突行为的识别，霸凌行为的特征提取和检测，危险动作的实时监测和告警
"""
import asyncio
import logging
import numpy as np
from datetime import datetime, timedelta
from typing import List, Dict, Optional, Tuple, Any, Set
from uuid import uuid4
import time
from collections import defaultdict, deque
from dataclasses import dataclass, field
from enum import Enum
import math

from schemas.pose_detection import (
    PoseEstimation, ActionRecognition, BehaviorAlert, BehaviorSeverity,
    JointType, ActionType, Keypoint
)
from schemas.person_detection import PersonDetectionResult
from core.config import get_settings

logger = logging.getLogger(__name__)
settings = get_settings()


class ConflictType(str, Enum):
    """冲突类型枚举"""
    PUSHING = "pushing"
    FIGHTING = "fighting"
    GRABBING = "grabbing"
    HITTING = "hitting"
    KICKING = "kicking"
    WRESTLING = "wrestling"
    BULLYING = "bullying"
    HARASSMENT = "harassment"
    THREATENING = "threatening"
    AGGRESSIVE_GESTURE = "aggressive_gesture"


class ConflictSeverity(str, Enum):
    """冲突严重程度枚举"""
    MINOR = "minor"
    MODERATE = "moderate"
    SERIOUS = "serious"
    SEVERE = "severe"
    CRITICAL = "critical"


class InteractionType(str, Enum):
    """交互类型枚举"""
    NEUTRAL = "neutral"
    FRIENDLY = "friendly"
    COMPETITIVE = "competitive"
    AGGRESSIVE = "aggressive"
    HOSTILE = "hostile"


@dataclass
class PersonInteraction:
    """人员交互信息"""
    person1_id: str
    person2_id: str
    interaction_type: InteractionType
    confidence: float
    distance: float
    relative_position: Tuple[float, float]
    duration: float
    start_time: datetime
    last_update: datetime
    features: Dict[str, float] = field(default_factory=dict)


@dataclass
class ConflictEvent:
    """冲突事件"""
    event_id: str
    conflict_type: ConflictType
    severity: ConflictSeverity
    involved_persons: List[str]
    start_time: datetime
    end_time: Optional[datetime]
    duration: Optional[float]
    location: Tuple[float, float]
    confidence: float
    evidence: Dict[str, Any]
    camera_id: str
    resolved: bool = False
    escalation_risk: float = 0.0


@dataclass
class BullyingPattern:
    """霸凌模式"""
    pattern_id: str
    pattern_name: str
    aggressor_behaviors: List[str]
    victim_behaviors: List[str]
    group_dynamics: Dict[str, Any]
    temporal_pattern: Dict[str, Any]
    confidence_threshold: float
    severity: ConflictSeverity


class GeometryAnalyzer:
    """几何分析器"""
    
    @staticmethod
    def calculate_distance(point1: Tuple[float, float], point2: Tuple[float, float]) -> float:
        """计算两点间距离"""
        return math.sqrt((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2)
    
    @staticmethod
    def calculate_angle(p1: Tuple[float, float], p2: Tuple[float, float], p3: Tuple[float, float]) -> float:
        """计算三点间角度"""
        v1 = (p1[0] - p2[0], p1[1] - p2[1])
        v2 = (p3[0] - p2[0], p3[1] - p2[1])
        
        dot_product = v1[0] * v2[0] + v1[1] * v2[1]
        magnitude1 = math.sqrt(v1[0]**2 + v1[1]**2)
        magnitude2 = math.sqrt(v2[0]**2 + v2[1]**2)
        
        if magnitude1 == 0 or magnitude2 == 0:
            return 0
        
        cos_angle = dot_product / (magnitude1 * magnitude2)
        cos_angle = max(-1, min(1, cos_angle))  # 确保在有效范围内
        
        return math.acos(cos_angle)
    
    @staticmethod
    def calculate_relative_position(person1_center: Tuple[float, float], 
                                  person2_center: Tuple[float, float]) -> Tuple[float, float]:
        """计算相对位置"""
        dx = person2_center[0] - person1_center[0]
        dy = person2_center[1] - person1_center[1]
        
        # 归一化
        distance = math.sqrt(dx**2 + dy**2)
        if distance > 0:
            return (dx / distance, dy / distance)
        return (0, 0)
    
    @staticmethod
    def is_facing_towards(pose1: PoseEstimation, pose2: PoseEstimation) -> bool:
        """判断person1是否面向person2"""
        # 获取肩膀关键点来判断朝向
        left_shoulder1 = pose1.get_keypoint(JointType.LEFT_SHOULDER)
        right_shoulder1 = pose1.get_keypoint(JointType.RIGHT_SHOULDER)
        
        if not (left_shoulder1 and right_shoulder1):
            return False
        
        # 计算肩膀中点
        shoulder_center1 = ((left_shoulder1.x + right_shoulder1.x) / 2,
                           (left_shoulder1.y + right_shoulder1.y) / 2)
        
        # 计算朝向向量（垂直于肩膀连线）
        shoulder_vector = (right_shoulder1.x - left_shoulder1.x,
                          right_shoulder1.y - left_shoulder1.y)
        facing_vector = (-shoulder_vector[1], shoulder_vector[0])  # 垂直向量
        
        # 计算到person2的向量
        person2_center = pose2.get_center_point()
        to_person2 = (person2_center[0] - shoulder_center1[0],
                     person2_center[1] - shoulder_center1[1])
        
        # 计算点积判断是否同向
        dot_product = facing_vector[0] * to_person2[0] + facing_vector[1] * to_person2[1]
        
        return dot_product > 0


class ConflictFeatureExtractor:
    """冲突特征提取器"""
    
    def __init__(self):
        self.geometry_analyzer = GeometryAnalyzer()
    
    def extract_pose_features(self, pose: PoseEstimation) -> Dict[str, float]:
        """提取姿态特征"""
        features = {}
        
        # 手臂特征
        left_shoulder = pose.get_keypoint(JointType.LEFT_SHOULDER)
        right_shoulder = pose.get_keypoint(JointType.RIGHT_SHOULDER)
        left_elbow = pose.get_keypoint(JointType.LEFT_ELBOW)
        right_elbow = pose.get_keypoint(JointType.RIGHT_ELBOW)
        left_wrist = pose.get_keypoint(JointType.LEFT_WRIST)
        right_wrist = pose.get_keypoint(JointType.RIGHT_WRIST)
        
        # 手臂抬起程度
        if left_shoulder and left_wrist:
            features['left_arm_raised'] = max(0, left_shoulder.y - left_wrist.y) / 100
        
        if right_shoulder and right_wrist:
            features['right_arm_raised'] = max(0, right_shoulder.y - right_wrist.y) / 100
        
        # 手臂张开程度
        if left_shoulder and right_shoulder and left_wrist and right_wrist:
            shoulder_width = abs(right_shoulder.x - left_shoulder.x)
            arm_span = abs(right_wrist.x - left_wrist.x)
            features['arm_spread'] = arm_span / shoulder_width if shoulder_width > 0 else 0
        
        # 肘部角度（攻击性姿态指标）
        if left_shoulder and left_elbow and left_wrist:
            left_elbow_angle = self.geometry_analyzer.calculate_angle(
                (left_shoulder.x, left_shoulder.y),
                (left_elbow.x, left_elbow.y),
                (left_wrist.x, left_wrist.y)
            )
            features['left_elbow_angle'] = left_elbow_angle
        
        if right_shoulder and right_elbow and right_wrist:
            right_elbow_angle = self.geometry_analyzer.calculate_angle(
                (right_shoulder.x, right_shoulder.y),
                (right_elbow.x, right_elbow.y),
                (right_wrist.x, right_wrist.y)
            )
            features['right_elbow_angle'] = right_elbow_angle
        
        # 身体姿态特征
        left_hip = pose.get_keypoint(JointType.LEFT_HIP)
        right_hip = pose.get_keypoint(JointType.RIGHT_HIP)
        
        # 身体倾斜度
        if left_shoulder and right_shoulder:
            shoulder_slope = (right_shoulder.y - left_shoulder.y) / (right_shoulder.x - left_shoulder.x) if right_shoulder.x != left_shoulder.x else 0
            features['body_tilt'] = abs(shoulder_slope)
        
        # 重心位置
        if left_hip and right_hip:
            hip_center = ((left_hip.x + right_hip.x) / 2, (left_hip.y + right_hip.y) / 2)
            if left_shoulder and right_shoulder:
                shoulder_center = ((left_shoulder.x + right_shoulder.x) / 2, (left_shoulder.y + right_shoulder.y) / 2)
                features['center_of_gravity_shift'] = abs(hip_center[0] - shoulder_center[0]) / 100
        
        # 腿部姿态
        left_knee = pose.get_keypoint(JointType.LEFT_KNEE)
        right_knee = pose.get_keypoint(JointType.RIGHT_KNEE)
        left_ankle = pose.get_keypoint(JointType.LEFT_ANKLE)
        right_ankle = pose.get_keypoint(JointType.RIGHT_ANKLE)
        
        # 站立稳定性
        if left_ankle and right_ankle:
            foot_distance = abs(right_ankle.x - left_ankle.x)
            features['stance_width'] = foot_distance / 100
        
        return features
    
    def extract_interaction_features(self, pose1: PoseEstimation, pose2: PoseEstimation) -> Dict[str, float]:
        """提取交互特征"""
        features = {}
        
        # 距离特征
        center1 = pose1.get_center_point()
        center2 = pose2.get_center_point()
        distance = self.geometry_analyzer.calculate_distance(center1, center2)
        features['distance'] = distance
        
        # 相对位置
        rel_pos = self.geometry_analyzer.calculate_relative_position(center1, center2)
        features['relative_x'] = rel_pos[0]
        features['relative_y'] = rel_pos[1]
        
        # 朝向特征
        features['person1_facing_person2'] = 1.0 if self.geometry_analyzer.is_facing_towards(pose1, pose2) else 0.0
        features['person2_facing_person1'] = 1.0 if self.geometry_analyzer.is_facing_towards(pose2, pose1) else 0.0
        features['mutual_facing'] = features['person1_facing_person2'] * features['person2_facing_person1']
        
        # 手臂指向特征
        features['arms_towards_each_other'] = self._calculate_arms_pointing_towards(pose1, pose2)
        
        # 身体姿态相似性
        pose1_features = self.extract_pose_features(pose1)
        pose2_features = self.extract_pose_features(pose2)
        
        # 计算姿态差异
        common_features = set(pose1_features.keys()) & set(pose2_features.keys())
        if common_features:
            pose_similarity = 1.0 - np.mean([abs(pose1_features[f] - pose2_features[f]) for f in common_features])
            features['pose_similarity'] = max(0, pose_similarity)
        
        # 高度差异
        features['height_difference'] = abs(center1[1] - center2[1]) / 100
        
        return features
    
    def _calculate_arms_pointing_towards(self, pose1: PoseEstimation, pose2: PoseEstimation) -> float:
        """计算手臂指向对方的程度"""
        score = 0.0
        count = 0
        
        center2 = pose2.get_center_point()
        
        # 检查pose1的手臂是否指向pose2
        arms = [
            (JointType.LEFT_SHOULDER, JointType.LEFT_ELBOW, JointType.LEFT_WRIST),
            (JointType.RIGHT_SHOULDER, JointType.RIGHT_ELBOW, JointType.RIGHT_WRIST)
        ]
        
        for shoulder_type, elbow_type, wrist_type in arms:
            shoulder = pose1.get_keypoint(shoulder_type)
            elbow = pose1.get_keypoint(elbow_type)
            wrist = pose1.get_keypoint(wrist_type)
            
            if shoulder and elbow and wrist:
                # 计算手臂方向向量
                arm_vector = (wrist.x - shoulder.x, wrist.y - shoulder.y)
                
                # 计算指向对方的向量
                to_person2 = (center2[0] - shoulder.x, center2[1] - shoulder.y)
                
                # 计算夹角
                arm_magnitude = math.sqrt(arm_vector[0]**2 + arm_vector[1]**2)
                to_person2_magnitude = math.sqrt(to_person2[0]**2 + to_person2[1]**2)
                
                if arm_magnitude > 0 and to_person2_magnitude > 0:
                    cos_angle = (arm_vector[0] * to_person2[0] + arm_vector[1] * to_person2[1]) / (arm_magnitude * to_person2_magnitude)
                    cos_angle = max(-1, min(1, cos_angle))
                    angle = math.acos(cos_angle)
                    
                    # 角度越小，指向性越强
                    pointing_score = max(0, 1 - angle / (math.pi / 2))  # 90度内有效
                    score += pointing_score
                    count += 1
        
        return score / count if count > 0 else 0.0


class ConflictClassifier:
    """冲突分类器"""
    
    def __init__(self):
        self.feature_extractor = ConflictFeatureExtractor()
        self.interaction_history: Dict[str, List[PersonInteraction]] = defaultdict(list)
        self.conflict_thresholds = self._initialize_thresholds()
        
        # 霸凌模式
        self.bullying_patterns = self._initialize_bullying_patterns()
    
    def _initialize_thresholds(self) -> Dict[str, Dict[str, float]]:
        """初始化冲突检测阈值"""
        return {
            'pushing': {
                'min_distance': 50,
                'max_distance': 150,
                'min_arm_raised': 0.3,
                'min_facing': 0.7,
                'min_confidence': 0.6
            },
            'fighting': {
                'min_distance': 30,
                'max_distance': 200,
                'min_arm_activity': 0.5,
                'min_mutual_facing': 0.8,
                'min_confidence': 0.7
            },
            'grabbing': {
                'min_distance': 20,
                'max_distance': 100,
                'min_arms_towards': 0.6,
                'min_confidence': 0.65
            },
            'threatening': {
                'min_distance': 100,
                'max_distance': 300,
                'min_aggressive_posture': 0.4,
                'min_facing': 0.6,
                'min_confidence': 0.5
            }
        }
    
    def _initialize_bullying_patterns(self) -> List[BullyingPattern]:
        """初始化霸凌模式"""
        return [
            BullyingPattern(
                pattern_id="physical_bullying",
                pattern_name="身体霸凌",
                aggressor_behaviors=["pushing", "hitting", "threatening"],
                victim_behaviors=["defensive", "retreating", "cowering"],
                group_dynamics={"size_imbalance": True, "repeated_interaction": True},
                temporal_pattern={"duration": 30, "frequency": "repeated"},
                confidence_threshold=0.8,
                severity=ConflictSeverity.SERIOUS
            ),
            BullyingPattern(
                pattern_id="intimidation",
                pattern_name="恐吓行为",
                aggressor_behaviors=["threatening", "aggressive_gesture"],
                victim_behaviors=["backing_away", "defensive"],
                group_dynamics={"power_imbalance": True},
                temporal_pattern={"duration": 15, "persistence": True},
                confidence_threshold=0.7,
                severity=ConflictSeverity.MODERATE
            )
        ]
    
    async def classify_interaction(self, pose1: PoseEstimation, pose2: PoseEstimation) -> Optional[PersonInteraction]:
        """分类人员交互"""
        # 提取交互特征
        features = self.feature_extractor.extract_interaction_features(pose1, pose2)
        
        # 判断交互类型
        interaction_type, confidence = await self._classify_interaction_type(features)
        
        if confidence > 0.5:
            interaction = PersonInteraction(
                person1_id=pose1.person_id,
                person2_id=pose2.person_id,
                interaction_type=interaction_type,
                confidence=confidence,
                distance=features['distance'],
                relative_position=(features['relative_x'], features['relative_y']),
                duration=0.0,  # 将在跟踪中更新
                start_time=datetime.now(),
                last_update=datetime.now(),
                features=features
            )
            
            return interaction
        
        return None
    
    async def _classify_interaction_type(self, features: Dict[str, float]) -> Tuple[InteractionType, float]:
        """分类交互类型"""
        distance = features.get('distance', float('inf'))
        mutual_facing = features.get('mutual_facing', 0)
        arms_towards = features.get('arms_towards_each_other', 0)
        
        # 敌对交互检测
        if distance < 150 and mutual_facing > 0.7 and arms_towards > 0.4:
            return InteractionType.HOSTILE, 0.8
        
        # 攻击性交互检测
        elif distance < 200 and (mutual_facing > 0.6 or arms_towards > 0.3):
            return InteractionType.AGGRESSIVE, 0.7
        
        # 竞争性交互检测
        elif distance < 300 and mutual_facing > 0.5:
            return InteractionType.COMPETITIVE, 0.6
        
        # 友好交互检测
        elif distance < 250 and mutual_facing > 0.3:
            return InteractionType.FRIENDLY, 0.5
        
        # 中性交互
        else:
            return InteractionType.NEUTRAL, 0.4
    
    async def detect_conflict(self, interactions: List[PersonInteraction]) -> List[ConflictEvent]:
        """检测冲突事件"""
        conflicts = []
        
        for interaction in interactions:
            if interaction.interaction_type in [InteractionType.AGGRESSIVE, InteractionType.HOSTILE]:
                conflict_type, severity, confidence = await self._analyze_conflict_details(interaction)
                
                if confidence > 0.6:
                    conflict = ConflictEvent(
                        event_id=str(uuid4()),
                        conflict_type=conflict_type,
                        severity=severity,
                        involved_persons=[interaction.person1_id, interaction.person2_id],
                        start_time=interaction.start_time,
                        end_time=None,
                        duration=interaction.duration,
                        location=((interaction.features.get('relative_x', 0) + 1) * 320,
                                (interaction.features.get('relative_y', 0) + 1) * 240),
                        confidence=confidence,
                        evidence={
                            'interaction_features': interaction.features,
                            'distance': interaction.distance,
                            'duration': interaction.duration
                        },
                        camera_id="unknown",  # 需要从上下文获取
                        escalation_risk=await self._calculate_escalation_risk(interaction)
                    )
                    
                    conflicts.append(conflict)
        
        return conflicts
    
    async def _analyze_conflict_details(self, interaction: PersonInteraction) -> Tuple[ConflictType, ConflictSeverity, float]:
        """分析冲突详情"""
        features = interaction.features
        distance = features.get('distance', float('inf'))
        arms_towards = features.get('arms_towards_each_other', 0)
        mutual_facing = features.get('mutual_facing', 0)
        
        # 推搡检测
        if (distance < 150 and arms_towards > 0.4 and mutual_facing > 0.6):
            return ConflictType.PUSHING, ConflictSeverity.MODERATE, 0.8
        
        # 打架检测
        elif (distance < 100 and arms_towards > 0.6 and mutual_facing > 0.8):
            return ConflictType.FIGHTING, ConflictSeverity.SERIOUS, 0.9
        
        # 抓取检测
        elif (distance < 80 and arms_towards > 0.7):
            return ConflictType.GRABBING, ConflictSeverity.MODERATE, 0.75
        
        # 威胁检测
        elif (distance < 300 and arms_towards > 0.3 and mutual_facing > 0.5):
            return ConflictType.THREATENING, ConflictSeverity.MINOR, 0.65
        
        # 攻击性手势
        else:
            return ConflictType.AGGRESSIVE_GESTURE, ConflictSeverity.MINOR, 0.6
    
    async def _calculate_escalation_risk(self, interaction: PersonInteraction) -> float:
        """计算冲突升级风险"""
        risk_factors = []
        
        # 距离因子（距离越近风险越高）
        distance_risk = max(0, 1 - interaction.distance / 200)
        risk_factors.append(distance_risk)
        
        # 持续时间因子
        duration_risk = min(1.0, interaction.duration / 60)  # 1分钟为满分
        risk_factors.append(duration_risk)
        
        # 交互强度因子
        intensity_risk = interaction.confidence
        risk_factors.append(intensity_risk)
        
        # 手臂活动因子
        arms_risk = interaction.features.get('arms_towards_each_other', 0)
        risk_factors.append(arms_risk)
        
        return np.mean(risk_factors)
    
    async def detect_bullying(self, interactions: List[PersonInteraction]) -> List[Dict[str, Any]]:
        """检测霸凌行为"""
        bullying_events = []
        
        # 按人员分组交互
        person_interactions = defaultdict(list)
        for interaction in interactions:
            person_interactions[interaction.person1_id].append(interaction)
            person_interactions[interaction.person2_id].append(interaction)
        
        # 检测霸凌模式
        for pattern in self.bullying_patterns:
            matches = await self._match_bullying_pattern(interactions, pattern)
            bullying_events.extend(matches)
        
        return bullying_events
    
    async def _match_bullying_pattern(self, interactions: List[PersonInteraction], pattern: BullyingPattern) -> List[Dict[str, Any]]:
        """匹配霸凌模式"""
        matches = []
        
        # 查找符合模式的交互组合
        aggressive_interactions = [
            i for i in interactions 
            if i.interaction_type in [InteractionType.AGGRESSIVE, InteractionType.HOSTILE]
        ]
        
        if len(aggressive_interactions) < 1:
            return matches
        
        # 简化的模式匹配
        for interaction in aggressive_interactions:
            if interaction.duration > pattern.temporal_pattern.get('duration', 0):
                confidence = interaction.confidence * 0.8  # 降低置信度
                
                if confidence >= pattern.confidence_threshold:
                    match = {
                        'pattern_id': pattern.pattern_id,
                        'pattern_name': pattern.pattern_name,
                        'aggressor_id': interaction.person1_id,
                        'victim_id': interaction.person2_id,
                        'confidence': confidence,
                        'severity': pattern.severity,
                        'duration': interaction.duration,
                        'evidence': {
                            'interaction_type': interaction.interaction_type.value,
                            'distance': interaction.distance,
                            'features': interaction.features
                        }
                    }
                    matches.append(match)
        
        return matches


class ConflictDetectionService:
    """冲突行为检测服务"""
    
    def __init__(self):
        self.classifier = ConflictClassifier()
        self.active_interactions: Dict[str, PersonInteraction] = {}
        self.conflict_events: List[ConflictEvent] = []
        self.bullying_events: List[Dict[str, Any]] = []
        self.behavior_alerts: List[BehaviorAlert] = []
        
        # 服务状态
        self._running = False
        self._analysis_task = None
        self.analysis_interval = 2.0  # 2秒分析一次
        
        # 统计信息
        self.stats = {
            'total_interactions': 0,
            'conflict_events': 0,
            'bullying_events': 0,
            'resolved_conflicts': 0
        }
    
    async def start_service(self):
        """启动服务"""
        if self._running:
            return
        
        self._running = True
        self._analysis_task = asyncio.create_task(self._analysis_loop())
        logger.info("Conflict detection service started")
    
    async def stop_service(self):
        """停止服务"""
        self._running = False
        if self._analysis_task:
            self._analysis_task.cancel()
            try:
                await self._analysis_task
            except asyncio.CancelledError:
                pass
        logger.info("Conflict detection service stopped")
    
    async def _analysis_loop(self):
        """分析循环"""
        while self._running:
            try:
                await self._periodic_analysis()
                await asyncio.sleep(self.analysis_interval)
            except asyncio.CancelledError:
                break
            except Exception as e:
                logger.error(f"Error in conflict analysis loop: {e}")
                await asyncio.sleep(1.0)
    
    async def _periodic_analysis(self):
        """周期性分析"""
        current_time = datetime.now()
        
        # 更新交互持续时间
        for interaction in self.active_interactions.values():
            interaction.duration = (current_time - interaction.start_time).total_seconds()
        
        # 清理过期交互
        expired_interactions = []
        for key, interaction in self.active_interactions.items():
            age = (current_time - interaction.last_update).total_seconds()
            if age > 30:  # 30秒未更新
                expired_interactions.append(key)
        
        for key in expired_interactions:
            del self.active_interactions[key]
        
        # 检测冲突
        if self.active_interactions:
            interactions = list(self.active_interactions.values())
            
            # 检测冲突事件
            conflicts = await self.classifier.detect_conflict(interactions)
            for conflict in conflicts:
                await self._handle_conflict_event(conflict)
            
            # 检测霸凌行为
            bullying_events = await self.classifier.detect_bullying(interactions)
            for event in bullying_events:
                await self._handle_bullying_event(event)
    
    async def _handle_conflict_event(self, conflict: ConflictEvent):
        """处理冲突事件"""
        # 检查是否已存在相似冲突
        existing_conflict = None
        for existing in self.conflict_events:
            if (set(existing.involved_persons) == set(conflict.involved_persons) and
                existing.conflict_type == conflict.conflict_type and
                not existing.end_time):
                existing_conflict = existing
                break
        
        if existing_conflict:
            # 更新现有冲突
            existing_conflict.end_time = datetime.now()
            existing_conflict.duration = (existing_conflict.end_time - existing_conflict.start_time).total_seconds()
            existing_conflict.confidence = max(existing_conflict.confidence, conflict.confidence)
        else:
            # 添加新冲突
            self.conflict_events.append(conflict)
            self.stats['conflict_events'] += 1
            
            # 生成告警
            await self._generate_conflict_alert(conflict)
        
        # 保持最近1000个冲突事件
        if len(self.conflict_events) > 1000:
            self.conflict_events = self.conflict_events[-1000:]
    
    async def _handle_bullying_event(self, event: Dict[str, Any]):
        """处理霸凌事件"""
        # 检查是否已存在相似霸凌事件
        existing_event = None
        for existing in self.bullying_events:
            if (existing.get('aggressor_id') == event.get('aggressor_id') and
                existing.get('victim_id') == event.get('victim_id') and
                existing.get('pattern_id') == event.get('pattern_id')):
                existing_event = existing
                break
        
        if not existing_event:
            event['event_id'] = str(uuid4())
            event['timestamp'] = datetime.now()
            self.bullying_events.append(event)
            self.stats['bullying_events'] += 1
            
            # 生成告警
            await self._generate_bullying_alert(event)
        
        # 保持最近500个霸凌事件
        if len(self.bullying_events) > 500:
            self.bullying_events = self.bullying_events[-500:]
    
    async def _generate_conflict_alert(self, conflict: ConflictEvent):
        """生成冲突告警"""
        severity_mapping = {
            ConflictSeverity.MINOR: BehaviorSeverity.SUSPICIOUS,
            ConflictSeverity.MODERATE: BehaviorSeverity.CONCERNING,
            ConflictSeverity.SERIOUS: BehaviorSeverity.DANGEROUS,
            ConflictSeverity.SEVERE: BehaviorSeverity.DANGEROUS,
            ConflictSeverity.CRITICAL: BehaviorSeverity.CRITICAL
        }
        
        alert = BehaviorAlert(
            alert_id=str(uuid4()),
            camera_id=conflict.camera_id,
            person_ids=conflict.involved_persons,
            behavior_type=conflict.conflict_type.value,
            severity=severity_mapping.get(conflict.severity, BehaviorSeverity.CONCERNING),
            confidence=conflict.confidence,
            description=f"检测到{conflict.conflict_type.value}行为",
            evidence={
                'conflict_type': conflict.conflict_type.value,
                'severity': conflict.severity.value,
                'duration': conflict.duration,
                'escalation_risk': conflict.escalation_risk,
                'location': conflict.location
            },
            timestamp=conflict.start_time,
            location=list(conflict.location),
            duration=conflict.duration
        )
        
        self.behavior_alerts.append(alert)
        
        # 保持最近1000个告警
        if len(self.behavior_alerts) > 1000:
            self.behavior_alerts = self.behavior_alerts[-1000:]
        
        logger.warning(f"Conflict alert generated: {conflict.conflict_type.value} involving {len(conflict.involved_persons)} persons")
    
    async def _generate_bullying_alert(self, event: Dict[str, Any]):
        """生成霸凌告警"""
        severity_mapping = {
            ConflictSeverity.MINOR: BehaviorSeverity.SUSPICIOUS,
            ConflictSeverity.MODERATE: BehaviorSeverity.CONCERNING,
            ConflictSeverity.SERIOUS: BehaviorSeverity.DANGEROUS,
            ConflictSeverity.SEVERE: BehaviorSeverity.DANGEROUS,
            ConflictSeverity.CRITICAL: BehaviorSeverity.CRITICAL
        }
        
        alert = BehaviorAlert(
            alert_id=str(uuid4()),
            camera_id="unknown",  # 需要从上下文获取
            person_ids=[event.get('aggressor_id', ''), event.get('victim_id', '')],
            behavior_type="bullying",
            severity=severity_mapping.get(event.get('severity', ConflictSeverity.MODERATE), BehaviorSeverity.CONCERNING),
            confidence=event.get('confidence', 0.7),
            description=f"检测到{event.get('pattern_name', '霸凌')}行为",
            evidence=event.get('evidence', {}),
            timestamp=event.get('timestamp', datetime.now()),
            duration=event.get('duration', 0)
        )
        
        self.behavior_alerts.append(alert)
        
        logger.warning(f"Bullying alert generated: {event.get('pattern_name')} - aggressor: {event.get('aggressor_id')}, victim: {event.get('victim_id')}")
    
    async def analyze_poses(self, poses: List[PoseEstimation], camera_id: str) -> Dict[str, Any]:
        """分析姿态中的冲突行为"""
        if len(poses) < 2:
            return {
                'interactions': [],
                'conflicts': [],
                'bullying_events': [],
                'alerts': []
            }
        
        interactions = []
        
        # 分析所有人员对之间的交互
        for i in range(len(poses)):
            for j in range(i + 1, len(poses)):
                interaction = await self.classifier.classify_interaction(poses[i], poses[j])
                if interaction:
                    interactions.append(interaction)
                    
                    # 更新活跃交互
                    key = f"{interaction.person1_id}_{interaction.person2_id}"
                    if key in self.active_interactions:
                        # 更新现有交互
                        existing = self.active_interactions[key]
                        existing.last_update = datetime.now()
                        existing.confidence = max(existing.confidence, interaction.confidence)
                        existing.features.update(interaction.features)
                    else:
                        # 添加新交互
                        self.active_interactions[key] = interaction
                        self.stats['total_interactions'] += 1
        
        # 检测冲突
        conflicts = await self.classifier.detect_conflict(interactions)
        
        # 检测霸凌
        bullying_events = await self.classifier.detect_bullying(interactions)
        
        return {
            'interactions': [self._interaction_to_dict(i) for i in interactions],
            'conflicts': [self._conflict_to_dict(c) for c in conflicts],
            'bullying_events': bullying_events,
            'alerts': [self._alert_to_dict(a) for a in self.behavior_alerts[-10:]]  # 最近10个告警
        }
    
    def _interaction_to_dict(self, interaction: PersonInteraction) -> Dict[str, Any]:
        """将交互转换为字典"""
        return {
            'person1_id': interaction.person1_id,
            'person2_id': interaction.person2_id,
            'interaction_type': interaction.interaction_type.value,
            'confidence': interaction.confidence,
            'distance': interaction.distance,
            'duration': interaction.duration,
            'features': interaction.features
        }
    
    def _conflict_to_dict(self, conflict: ConflictEvent) -> Dict[str, Any]:
        """将冲突转换为字典"""
        return {
            'event_id': conflict.event_id,
            'conflict_type': conflict.conflict_type.value,
            'severity': conflict.severity.value,
            'involved_persons': conflict.involved_persons,
            'confidence': conflict.confidence,
            'duration': conflict.duration,
            'escalation_risk': conflict.escalation_risk,
            'location': conflict.location
        }
    
    def _alert_to_dict(self, alert: BehaviorAlert) -> Dict[str, Any]:
        """将告警转换为字典"""
        return {
            'alert_id': alert.alert_id,
            'behavior_type': alert.behavior_type,
            'severity': alert.severity.value,
            'confidence': alert.confidence,
            'description': alert.description,
            'person_ids': alert.person_ids,
            'timestamp': alert.timestamp.isoformat(),
            'resolved': alert.resolved
        }
    
    async def get_conflict_events(
        self,
        camera_id: Optional[str] = None,
        conflict_type: Optional[ConflictType] = None,
        severity: Optional[ConflictSeverity] = None,
        start_time: Optional[datetime] = None,
        end_time: Optional[datetime] = None,
        limit: int = 100
    ) -> List[ConflictEvent]:
        """获取冲突事件"""
        events = self.conflict_events
        
        # 过滤条件
        if camera_id:
            events = [e for e in events if e.camera_id == camera_id]
        
        if conflict_type:
            events = [e for e in events if e.conflict_type == conflict_type]
        
        if severity:
            events = [e for e in events if e.severity == severity]
        
        if start_time:
            events = [e for e in events if e.start_time >= start_time]
        
        if end_time:
            events = [e for e in events if e.start_time <= end_time]
        
        # 按时间倒序排列
        events.sort(key=lambda x: x.start_time, reverse=True)
        
        return events[:limit]
    
    async def get_bullying_events(
        self,
        aggressor_id: Optional[str] = None,
        victim_id: Optional[str] = None,
        pattern_id: Optional[str] = None,
        limit: int = 100
    ) -> List[Dict[str, Any]]:
        """获取霸凌事件"""
        events = self.bullying_events
        
        # 过滤条件
        if aggressor_id:
            events = [e for e in events if e.get('aggressor_id') == aggressor_id]
        
        if victim_id:
            events = [e for e in events if e.get('victim_id') == victim_id]
        
        if pattern_id:
            events = [e for e in events if e.get('pattern_id') == pattern_id]
        
        # 按时间倒序排列
        events.sort(key=lambda x: x.get('timestamp', datetime.min), reverse=True)
        
        return events[:limit]
    
    async def get_behavior_alerts(
        self,
        camera_id: Optional[str] = None,
        severity: Optional[BehaviorSeverity] = None,
        resolved: Optional[bool] = None,
        limit: int = 100
    ) -> List[BehaviorAlert]:
        """获取行为告警"""
        alerts = self.behavior_alerts
        
        # 过滤条件
        if camera_id:
            alerts = [a for a in alerts if a.camera_id == camera_id]
        
        if severity:
            alerts = [a for a in alerts if a.severity == severity]
        
        if resolved is not None:
            alerts = [a for a in alerts if a.resolved == resolved]
        
        # 按时间倒序排列
        alerts.sort(key=lambda x: x.timestamp, reverse=True)
        
        return alerts[:limit]
    
    def get_active_interactions(self) -> List[PersonInteraction]:
        """获取活跃交互"""
        return list(self.active_interactions.values())
    
    def get_statistics(self) -> Dict[str, Any]:
        """获取统计信息"""
        return {
            'total_interactions': self.stats['total_interactions'],
            'active_interactions': len(self.active_interactions),
            'conflict_events': self.stats['conflict_events'],
            'bullying_events': self.stats['bullying_events'],
            'resolved_conflicts': self.stats['resolved_conflicts'],
            'total_alerts': len(self.behavior_alerts),
            'unresolved_alerts': len([a for a in self.behavior_alerts if not a.resolved])
        }
    
    async def resolve_conflict(self, event_id: str) -> bool:
        """解决冲突"""
        for conflict in self.conflict_events:
            if conflict.event_id == event_id:
                conflict.resolved = True
                conflict.end_time = datetime.now()
                if conflict.start_time:
                    conflict.duration = (conflict.end_time - conflict.start_time).total_seconds()
                
                self.stats['resolved_conflicts'] += 1
                logger.info(f"Conflict resolved: {event_id}")
                return True
        
        return False
    
    async def resolve_alert(self, alert_id: str) -> bool:
        """解决告警"""
        for alert in self.behavior_alerts:
            if alert.alert_id == alert_id:
                alert.resolved = True
                logger.info(f"Alert resolved: {alert_id}")
                return True
        
        return False


# 全局冲突检测服务实例
conflict_detection_service = ConflictDetectionService()